package com.ywl.study.transaction.aspect;

import com.ywl.study.transaction.connection.DistrctConnection;
import com.ywl.study.transaction.transaction.DistirctTransactionManager;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;

@Component
@Aspect
@Slf4j
public class DistractDataSourceAspect {

    @Around("execution(* javax.sql.DataSource.getConnection(..))")
    public Connection around(ProceedingJoinPoint point) throws Throwable {
        log.info("进入DistractDataSourceAspect 切面。。。。。");
        if(DistirctTransactionManager.getCurrentGroupId()!=null){
            System.out.println("获得分布式connection");
            //如果当前线程有groupId,或者当前方法是有@GlobalTransaction注解，则采用分布式Connection
            Connection connection =(Connection)point.proceed();
            connection.setAutoCommit(false);
            DistrctConnection distrctConnection=new DistrctConnection(connection);
            return distrctConnection;
        }else{
            return (Connection) point.proceed();
        }
    }

}
